﻿// <copyright file="SetIdBase.cs" company="Hallvard Korsgaard">
//  Microsoft Public License (Ms-PL). See license details here: http://enoceannet.codeplex.com/license
// </copyright>
// <author>Hallvard Korsgaard</author>

namespace EnOcean.Command
{
  using System;

  /// <summary>
  /// With this command the user can rewrite its ID range base number. The information of the 25 most significant bits is stored in EEPROM.
  /// The allowed ID range is from 0xFF800000 to 0xFFFFFFFF. This command can only be used a maximum number of 10 times. After successfully ID range reprogramming, the TCM answers with
  /// an Ok telegram. If reprogramming was not successful, the TCM answers sending an Error telegram if the maximum number of 10 times is exceeded or an IdOutOfRangeError telegram if the ID range
  /// base is not within the allowed range.
  /// </summary>
  [Serializable]
  public class SetIdBase : CommandTelegram
  {
    /// <summary>
    /// Variable for the IdBase property.
    /// </summary>
    private long idBase;

    /// <summary>
    /// Initializes a new instance of the SetIdBase class.
    /// </summary>
    /// <param name="idBase">The 32 bit transmitter ID. The ID must be in the range 0 to 0xffffffff inclusive.</param>
    public SetIdBase(long idBase)
    {
      this.IdBase = idBase;
    }

    /// <summary>
    /// Initializes a new instance of the SetIdBase class.
    /// </summary>
    public SetIdBase()
    {
      this.IdBase = 0xff800000;
    }

    /// <summary>
    /// Gets or sets the 32 bit transmitter ID. The ID must be in the range 0 to 0xffffffff inclusive.
    /// </summary>
    public long IdBase
    {
      get
      {
       return this.idBase;
      }
      
      set
      {
        if (value >= 0xff800000 && value <= 0xffffffff)
        {
          this.idBase = value;
        }
        else
        {
          throw new ArgumentOutOfRangeException("Id", "must be a 32 bit value in the range 0xff800000 to 0xffffffff inclusive");
        }
      }
    }

    /// <summary>
    /// Creates the byte format of the message.
    /// </summary>
    /// <param name="message">A byte array of length 14 to hold the message contents.</param>
    protected internal override void CreateMessage(byte[] message)
    {
      byte[] i;

      base.CreateMessage(message);
      message[3] = (byte)CommandType.SetIdBase;
      i = BitConverter.GetBytes(this.IdBase);
      
      message[4] = i[3]; // Id 3
      message[5] = i[2]; // Id 2
      message[6] = i[1]; // Id 1
      message[7] = i[0]; // Id 0
    }
  }
}
